package com.example.core.dao;

import org.apache.commons.collections.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.core.query.BaseQuery;

public interface BaseDao<T extends com.example.core.model.BaseEntity, ID extends java.io.Serializable> extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T> {

	@Deprecated
	public default PageResult<T> findPagesByExample(T example, Pageable pageable) {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>(example);
		return findPages(queryWrapper, pageable);
	}

	public default PageResult<T> findPages(QueryWrapper<T> queryWrapper, Pageable pageable) {
		sortify(queryWrapper, pageable);
		IPage<T> page = selectPage(new Page<T>(pageable.getPageNo(), pageable.getPageSize()), queryWrapper);
		return new PageResult<T>(page.getRecords(), page.getTotal());
	}

	public default QueryWrapper<T> createQueryWithBaseIf(BaseQuery baseQuery) {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>();
		if (baseQuery.getId() != null) {
			queryWrapper.eq("id", baseQuery.getId());
		}
		if (CollectionUtils.isNotEmpty(baseQuery.getIds())) {
			queryWrapper.in("id", baseQuery.getIds());
		}
		if (baseQuery.getCreatedAtFrom() != null) {
			queryWrapper.ge("created_at", baseQuery.getCreatedAtFrom());
		}
		if (baseQuery.getCreatedAtTo() != null) {
			queryWrapper.lt("created_at", baseQuery.getCreatedAtTo());
		}
		return queryWrapper;
	}

	public default void sortify(QueryWrapper<T> queryWrapper, Pageable pageable) {
		String sort = pageable.getSort();
		if (sort == null || sort.isEmpty()) {
			sort = "id DESC";
		}
		queryWrapper.last("ORDER BY " + sort);
	}

}
